package com.dreamfire.display.display2D.core
{
	import com.dreamfire.asset.AssetManager;
	
	import flash.display.Bitmap;
	import flash.display.BitmapData;
	import flash.display.LoaderInfo;
	import flash.events.Event;
	import flash.events.EventDispatcher;
	import flash.events.IOErrorEvent;
	import flash.events.ProgressEvent;
	import flash.geom.Vector3D;
	
	public class Tile2D extends Bitmap
	{
		public static const MAP_TILE_RESOURCE:String = "tile/";
		
		private var _position:Vector3D = new Vector3D();
		
		protected var _size:uint;
		
		private var _mapId:String;
		private var _tileX:int;
		private var _tileY:int;
		
		public function get mapId():String
		{
			return _mapId;
		}
		
		public function get tileX():int
		{
			return _tileX;
		}
		
		public function get tileY():int
		{
			return _tileY;
		}
		
		public function get size():int
		{
			return _size;
		}
		
		public function set position( value:Vector3D ):void
		{
			_position = value;
			
			x = value.x;
			y = value.z;
		}
		
		public function get position():Vector3D
		{
			return _position;
		}
		
		public function Tile2D(size:uint = 32, bitmapData:BitmapData=null, pixelSnapping:String="auto", smoothing:Boolean=false)
		{
			this._size = size;
			if( !bitmapData )
				bitmapData = new BitmapData(size, size, false, 0);
			super(bitmapData, pixelSnapping, smoothing);
		}
		
		public function loadResource( mapid:String, tileX:int, tileY:int ):void
		{
			var url:String = MAP_TILE_RESOURCE + mapid + "_x" + tileX + "_y" + tileY + ".jpg";
			var data:BitmapData = AssetManager.instance.getAsset( url ) as BitmapData;
			if( data )
				bitmapData = data;
			else
				AssetManager.instance.load( url, loadComplete, loadProgress, ioerror );
		}
		
		protected function loadComplete( evt:Event ):void
		{
			var loaderinfo:LoaderInfo = evt.target as LoaderInfo;
			var bmp:Bitmap = loaderinfo.content as Bitmap;
			bitmapData = bmp.bitmapData;
			AssetManager.instance.destroyLoaderListener( loaderinfo, loadComplete, loadProgress, ioerror );
		}
		
		protected function loadProgress( evt:ProgressEvent ):void
		{
			
		}
		
		protected function ioerror( evt:IOErrorEvent ):void
		{
			AssetManager.instance.destroyLoaderListener( evt.target as LoaderInfo, loadComplete, loadProgress, ioerror );
		}
	}
}